import { PrismaClient } from '@prisma/client'


const fs = require('fs');
const {v4 : uuid} = require('uuid');
const serverManager = require("./serverManager");
const messageManage = require("./messageManage");

function ensureDirExistence(filePath) {

    // 确保目录存在
    if (!fs.existsSync(filePath)) {
        fs.mkdirSync(filePath, { recursive: true });
    }

}

function ensureFileExistence(filePath) {
    // 确保文件存在
    if (!fs.existsSync(filePath)) {
        fs.writeFileSync(filePath, '', 'utf8'); // 创建空文件
        console.log(`File ${filePath} created.`);
    } else {
        console.log(`File ${filePath} already exists.`);
    }
}

class Device {

    constructor(data) {
        this.data = data;
        if (data) {
            this.id = data.id;
            this.port = data.port;
        }
    }

    /**
     * 保存
     */
    merge() {
        if (!this.data) {
            return;
        }
        fs.writeFileSync(`store/device/${this.id}.json`, JSON.stringify(this.data));
    }

    start() {
        if (this.server) {
            this.closeServer();
        }
        this.startServer();
    }

    startServer() {

        const server = serverManager.create(this.port, function(data, socket) {
            const msg = data.toString();
            if (msg==='$$list') {
                socket.write(JSON.stringify(messageManage.getList(this.port)));
                return;
            }
            messageManage.addMessage(this.port, msg);
        });
        server.start();
        this.server = server;
    }

    closeServer() {
        if (!this.server) {
            console.warn('server not exists');
            return;
        }
        this.server.close();
        this.server = null;
    }
}

const flowMapping = {};

module.exports = {

    async init() {

        const prisma = new PrismaClient()

        const devices = await prisma.device.findMany();
        console.log("devices",devices)

        // const filePath = `store/flows/`;
        // ensureDirExistence(filePath);
        // fs.readdirSync(filePath).forEach(f => {
        //     if (f.endsWith('.json')) {
        //         const content = fs.readFileSync(filePath + '/' + f, 'utf-8');
        //         const data = JSON.parse(content);
        //         const flow = new Flow(data);
        //         const uuid = flow.uuid;
        //         flowMapping[uuid] = flow;
        //     }
        // });
        // this.startAll();
    },
    startAll() {
        for(const key in flowMapping) {
            const flow = flowMapping[key];
            flow.start();
        }
    },
    create(data) {
        const flow = new Flow(data);
        const uuid = flow.uuid;
        flow.merge();
        flowMapping[uuid] = flow;
        return flow;
    },
    start(uuid) {
        const flow = flowMapping[uuid];
        flow.start();
    }
};